var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


var app = express();

let roomLists=[]

const io = require("socket.io")(3004,{cors:true});

io.on("connection", socket => {

  socket.on("join", (data) => {
    console.log(data);
    io.emit("join"+data.roomId, data);
  });

  socket.on("roomUpdate", (data) => {
    for(let i=0;i<roomLists.length;i++){
      if(roomLists[i].roomId==data.roomId){
        roomLists[i].time=Date.now();
      }
    }

    let catchRooms=roomLists.filter((item)=>{return item.roomId==data.roomId})

    if(catchRooms.length==0){
      roomLists.push(
        {
        ...data,
        time:Date.now()
        }
      )
    }
  });

  socket.on("setOffer", (data) => {
    console.log(data);
    io.emit("setOffer"+data.uid, data);
  });

  socket.on("setAnswer", (data) => {
    console.log(data);
    io.emit("setAnswer"+data.roomId, data);
  });

  socket.on("disconnect", (data) => {
    console.log("链接断开",data)
  })
});

setInterval(()=>{
  for(let i=0;i<roomLists.length;i++){
    if(Date.now()-roomLists[i].time>5000){
      console.log("服务器"+roomLists[i].roomId+"断开")
      roomLists.splice(i, 1);
    }
  }
  io.emit("roomUpdate", roomLists);
},500)

app.listen(8083)

console.log("成功")

module.exports = app;
